
package com.wuye.action;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Getter;
import lombok.Setter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.wuye.common.util.bean.EntityCopyUtil;
import com.wuye.common.util.numeric.NumericUtil;
import com.wuye.common.util.string.StrUtil;
import com.wuye.common.vo.CommonObjectVO;
import com.wuye.common.vo.PageInfo;
import com.wuye.common.vo.RetVO;
import com.wuye.constants.BaseConstants;
import com.wuye.entity.Building;
import com.wuye.entity.Community;
import com.wuye.entity.PropertyCompany;
import com.wuye.entity.Room;
import com.wuye.entity.User;
import com.wuye.services.RoomServiceManager;
import com.wuye.util.ExcelUtil;

public class RoomAction extends ActionSupport {
	private Logger log = Logger.getLogger(RoomAction.class);
	@Autowired
	private RoomServiceManager roomServiceManager;
	// @Autowired
	// private Manager baseManager;
	@Setter
	@Getter
	private String inParma = "";
	private String returnInfo = "";
	private int page;
	@Setter
	@Getter
	private String suc_info;
	@Setter
	@Getter
	private File fileupload;// 这里的"fileName"一定要与表单中的文件域名相同
	@Setter
	@Getter
	private String fileuploadContentType;// 格式同上"fileName"+ContentType
	@Setter
	@Getter
	private String fileuploadFileName;// 格式同上"fileName"+FileName

	public String saveRoom() {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> inMap = new HashMap<String, Object>();
		try {
			JSONObject json = JSONObject.fromObject(inParma);
			JSONArray jsonArray = json.getJSONArray("data");
			if (jsonArray != null && jsonArray.size() > 0) {
				inMap.put("room", jsonArray);

				RetVO retVo = roomServiceManager.save(inMap);
				if (BaseConstants.RET_TRUE.equals(retVo.getResult())) {
					map.put("result", "true");
					map.put("msg", "保存信息成功");
				} else {
					map.put("result", "false");
					map.put("msg", "保存信息失败");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "false");
			map.put("msg", "保存信息失败:" + e.getMessage());
			log.info(e.getMessage());
		}
		JSONObject jsontip = JSONObject.fromObject(map);
		suc_info = jsontip.toString();
		return SUCCESS;

	}

	public String getRoomList() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			boolean isLogin = false;

			if (!StrUtil.isNullOrEmpty(inParma)) {
				JSONObject json = JSONObject.fromObject(inParma);
				// 有传isQueryOne代表查询单独一个
				if (!StrUtil.isNullOrEmpty(json.get("isQueryOne"))
						&& "yes".equals(json.get("isQueryOne").toString())
						&& !StrUtil.isNullOrEmpty(json.get("roomId"))) {
					map.put("roomId", json.get("roomId"));
				}
				// 界面展示模糊查询的时候使用
				if (!StrUtil.isNullOrEmpty(json.get("roomName"))) {
					map.put("roomName", json.get("roomName"));
				}
				if (StrUtil.isNullOrEmpty(page) || page < 1) {
					page = 1;
				}
			}
			PageInfo pageInfo = roomServiceManager.getRoomList(map, page,
					BaseConstants.DEFAULT_PAGE_PER_COUNT);
			if (pageInfo != null) {
				map.put("pageInfo", pageInfo);
			}
			map.put("result", "true");
			map.put("msg", "物业公司查询成功!");
		} catch (Exception e) {
			map.put("result", "false");
			map.put("msg", e.getMessage());
		}
		JSONObject jsontip = JSONObject.fromObject(map);
		returnInfo = jsontip.toString();
		return "list_Room";

	}

	public String getRoom() {
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			JSONObject json = JSONObject.fromObject(inParma);
			if (!StrUtil.isNullOrEmpty(json.get("account"))) {
				// 用户手机号查询
				paramMap.put("account", StrUtil.strnull(json.get("account")));
			}
			if (!StrUtil.isNullOrEmpty(json.get("roomId"))) {
				paramMap.put("roomId",
						NumericUtil.nullToIntegerZero(json.get("roomId")));
			}
			if (!StrUtil.isNullOrEmpty(json.get("buildingId"))) {
				paramMap.put("buildingId",
						NumericUtil.nullToIntegerZero(json.get("buildingId")));
			}
			if (!StrUtil.isNullOrEmpty(json.get("communityId"))) {
				paramMap.put("communityId",
						NumericUtil.nullToIntegerZero(json.get("communityId")));
			}
			Object communityId = ActionContext.getContext().getSession()
					.get("communityId");
			if (communityId != null) {
				paramMap.put("communityId", (Integer) communityId);
			}

			String type = StrUtil.strnull(json.get("qryType"));
			paramMap.put("qryType", type);
			RetVO retvo = null;
			retvo = roomServiceManager.getRoom(paramMap,
					NumericUtil.nullToZero(page), 12);

			/*
			 * if (type.equals("getSimpleBuildingBycommunity")){ retvo =
			 * roomServiceManager.getSimpleBuildingBycommunity(paramMap); }else{
			 * retvo =
			 * roomServiceManager.getBuilding(paramMap,NumericUtil.nullToZero
			 * (page), 12); }
			 */

			if (retvo != null
					&& BaseConstants.RET_TRUE.equals(retvo.getResult())) {
				if (retvo.getObject() != null) {
					Map<String, Object> out = (Map<String, Object>) retvo
							.getObject();
					JSONArray jsArray = (JSONArray) out.get("jsArray");
					int pgcount = (Integer) out.get("pageCount");
					retMap.put("data", jsArray);
					retMap.put("pageCount", pgcount);
				}
				retMap.put("result", "true");
				retMap.put("msg", "信息查询成功!");

			} else {
				retMap.put("result", "false");
				retMap.put("msg", "信息查询失败!");
			}

			// JsonConfig jsonConfig = new JsonConfig();

		} catch (Exception e) {
			e.printStackTrace();
			retMap.put("result", "false");
			retMap.put("msg", "信息查询失败:" + e.getMessage());
		}
		/*
		 * JsonConfig jsonConfig = SpringUtil.getBean("jsonConfig");
		 * 
		 * //jsonConfig.setJsonPropertyFilter(new InvisibleFilter(true,"no"));
		 * //jsonConfig.setJsonPropertyFilter(new HibernatePropertyFilter());
		 * //jsonConfig.setExcludes(new
		 * String[]{"handler","hibernateLazyInitializer"});
		 * jsonConfig.registerJsonValueProcessor(Timestamp.class, new
		 * JsonDateValueProcessor("yyyy-MM-dd hh:mm:ss"));
		 */
		JSONObject jsonArr = JSONObject.fromObject(retMap);
		suc_info = jsonArr.toString();
		return SUCCESS;
	}

	/**
	 * 删除房间
	 */
	public String removeRoom() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (!StrUtil.isNullOrEmpty(inParma)) {
				map.put("roomIdArray", JSONArray.fromObject(inParma));
				roomServiceManager.removeRoom(map);
				map.put("key", "success");
			}
		} catch (Exception e) {
			map.put("result", "false");
			map.put("msg", e.getMessage());
		}
		JSONObject jsontip = JSONObject.fromObject(map);
		suc_info = jsontip.toString();
		return SUCCESS;
	}

	/**
	 * 获取登录物业用户默认的物业公司
	 */
	public String getDefaultPropertyCompany() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			User user = (User) ActionContext.getContext().getSession()
					.get("user");
		} catch (Exception e) {
			map.put("result", "false");
			map.put("msg", e.getMessage());
		}
		JSONObject jsontip = JSONObject.fromObject(map);
		returnInfo = jsontip.toString();
		return "default_user";
	}

	public String addPartyInfos() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			JSONObject json = JSONObject.fromObject(inParma);
			JSONObject roomJson = json.getJSONObject("room");
			JSONArray partryInfoArray = json.getJSONArray("partyInfos");
			Room room = new Room();
			EntityCopyUtil.populate(room, roomJson, new String[] { "roomId" });
			RetVO retVo = roomServiceManager.addPartyInfos(room,
					partryInfoArray);
			map.put("result",
					BaseConstants.RET_TRUE.equals(retVo.getResult()) ? "true"
							: "false");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "false");
			log.info(e.getMessage());
		}
		JSONObject jsontip = JSONObject.fromObject(map);
		suc_info = jsontip.toString();
		return SUCCESS;

	}
	
	public String getRoomInfo()
	{
		JSONObject jsonObj = JSONObject.fromObject(inParma);
		
		try 
		{
			int unitId = Integer.parseInt(jsonObj.getString("unitId"));
			jsonObj.clear();
			jsonObj.put("found", 1);
			
			List <CommonObjectVO> roomInfo = roomServiceManager.getRoomInfo(unitId);
			
			if (roomInfo != null && roomInfo.size() > 0)
			{
				jsonObj.put("data", JSONArray.fromObject(roomInfo).toString());
			}
			else
			{
				jsonObj.put("found", 0);
			}
		} 
		catch (Exception e)
		{
			jsonObj.clear();
			jsonObj.put("found", 0);
			e.printStackTrace();
		}
		finally
		{
			suc_info = jsonObj.toString();
		}
		
		log.debug(suc_info);
		
		return SUCCESS;
	}	

	public String getReturnInfo() {
		return returnInfo;
	}

	public void setReturnInfo(String returnInfo) {
		this.returnInfo = returnInfo;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public String uploadFile() {
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> inMap = new HashMap<String, Object>();

		if (fileupload != null) {
			try {
				RetVO roomRet = this.checkImport(fileupload);
				if (BaseConstants.RET_TRUE.equals(roomRet.getResult())) {
					JSONArray roomArray = (JSONArray) roomRet.getObject();
					inMap.put("room", roomArray);
					RetVO retVo = roomServiceManager.save(inMap);
					if (BaseConstants.RET_TRUE.equals(retVo.getResult())) {
						retMap.put("result", "true");
						retMap.put("msg", "保存信息成功");
					} else {
						retMap.put("result", "false");
						retMap.put("msg", "保存信息失败");
					}
				} else {
					retMap.put("result", "false");
					retMap.put("msg", roomRet.getRetMsg());
				}
			} catch (Exception e) {
				log.info(e.getMessage());
				retMap.put("result", "false");
				retMap.put("msg", "保存失败");
			}
		}
		JSONObject jsonArr = JSONObject.fromObject(retMap);
		suc_info = jsonArr.toString();
		return SUCCESS;
	}

	private RetVO checkImport(File file) {
		RetVO retVo = RetVO.newInstance(BaseConstants.RET_TRUE, "");
		try {
			String[][] dataArray = ExcelUtil.readExcel(file);
			if (dataArray == null || dataArray.length == 0) {
				retVo.setResult(BaseConstants.RET_FALSE);
				retVo.setRetMsg("导入的文件内容为空!");
				return retVo;
			}
			JSONArray roomArray = new JSONArray();
			for (int i = 0; i < dataArray.length; i++) {
				String companyName = StrUtil.strTrim(dataArray[i][0]);
				String communityName = StrUtil.strTrim(dataArray[i][1]);
				String buildingName = StrUtil.strTrim(dataArray[i][2]);
				String unitName = StrUtil.strTrim(dataArray[i][3]);
				String roomNbr = StrUtil.strTrim(dataArray[i][4]);
				String floor = StrUtil.strTrim(dataArray[i][5]);
				String partyName = StrUtil.strTrim(dataArray[i][6]);
				String account = StrUtil.strTrim(dataArray[i][7]);

				if ("".equals(buildingName)) {
					retVo.setResult(BaseConstants.RET_FALSE);
					retVo.setRetMsg("楼栋不能为空");
					return retVo;
				}
				/*
				 * if (nbrSet.contains(account)) {
				 * retVo.setResult(BaseConstants.RET_FALSE);
				 * retVo.setRetMsg(String.format("文件中的手机号[s%]重复", account));
				 * return retVo; }
				 */
				Map<String, Object> inMap = new HashMap<String, Object>();
				PropertyCompany company;
				Community community = null;
				User user = (User) ActionContext.getContext().getSession()
						.get("user");
				if (BaseConstants.USER_TYPE_10.equals(user.getUserType())) {
					if ("".equals(companyName)) {
						retVo.setResult(BaseConstants.RET_FALSE);
						retVo.setRetMsg("物业公司名称不能为空");
						return retVo;
					}
					company = PropertyCompany.getDao().getCompanyByName(
							companyName);

					/*
					 * if (company == null){
					 * retVo.setResult(BaseConstants.RET_FALSE);
					 * retVo.setRetMsg(String.format("物业公司[s%]不存在",
					 * companyName)); return retVo; }
					 */
				} else {
					company = user.getOwnerCompany();
				}

				if (company == null) {
					retVo.setResult(BaseConstants.RET_FALSE);
					retVo.setRetMsg("物业公司不存在");
					return retVo;
				}

				if (BaseConstants.USER_TYPE_10.equals(user.getUserType())) {
					inMap.clear();
					inMap.put("companyId", company.getId());
					inMap.put("communityName", communityName);

					PageInfo pg = Community.getDao().getCommunity(inMap, 1, 1);
					List<Object> dataList = pg.getDataList();
					if (dataList != null && dataList.size() > 0) {
						community = (Community) dataList.get(0);
					}
				} else {
					Object communityId = ActionContext.getContext()
							.getSession().get("communityId");
					if (communityId != null) {
						community = (Community) Community.getDao().getObject(
								Community.class, (Integer) communityId);
					}
				}

				if (community == null) {
					retVo.setResult(BaseConstants.RET_FALSE);
					retVo.setRetMsg("小区不存在");
					return retVo;
				}

				Building building = null;
				inMap.clear();
				inMap.put("communityId", community.getId());
				inMap.put("buildingName", buildingName);
				PageInfo pg = Building.getDao().getBuilding(inMap, 1, 1);
				List<Object> dataList = pg.getDataList();
				if (dataList != null && dataList.size() > 0) {
					building = (Building) dataList.get(0);
				}

				if (building == null) {
					retVo.setResult(BaseConstants.RET_FALSE);
					retVo.setRetMsg("楼栋不存在");
					return retVo;
				}

				if (building.getOwnerBuilding() == null) {
					if (!StrUtil.isNullOrEmpty(unitName)) {
						Building unit = null;
						inMap.clear();
						inMap.put("ownerBuilding", building.getId());
						inMap.put("buildingName", unitName);
						pg = Building.getDao().getBuilding(inMap, 1, 1);
						dataList = pg.getDataList();
						if (dataList != null && dataList.size() > 0) {
							unit = (Building) dataList.get(0);
						}

						if (unit == null) {
							retVo.setResult(BaseConstants.RET_FALSE);
							retVo.setRetMsg("单元不存在");
							return retVo;
						}
						building = unit;
					}
				}

				JSONObject roomjs = new JSONObject();
				JSONObject partyInfo = new JSONObject();
				JSONObject userjs = new JSONObject();
				partyInfo.put("partyName", partyName);
				userjs.put("account", account);
				partyInfo.put("user", userjs);

				JSONObject communityJs = new JSONObject();
				communityJs.put("communityId", community.getId());
				JSONObject companyJs = new JSONObject();
				companyJs.put("companyId", company.getId());
				communityJs.put("company", companyJs);
				
				JSONArray roomPartyRel = new JSONArray();
				JSONObject roomPartyRelObj = new JSONObject();
				roomPartyRelObj.put("partyInfo", partyInfo);
				roomPartyRelObj.put("relType", "10");
				roomPartyRel.add(roomPartyRelObj);
				roomjs.put("roomPartyRel", roomPartyRel);

				roomjs.put("roomNbr", roomNbr);
				roomjs.put("floor", floor);
				roomjs.put("community", communityJs);
				JSONObject buildingJs = new JSONObject();
				buildingJs.put("buildingId", building.getId());
				roomjs.put("building", buildingJs);
				roomArray.add(roomjs);
			}
			retVo.setObject(roomArray);
		} catch (Exception e) {
			retVo.setResult(BaseConstants.RET_FALSE);
			retVo.setRetMsg("导入的文件时出错!");
		}

		return retVo;
	}
}
